package zhjb.platform.web.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.config.DefaultSettings;

import zhjb.platform.web.BaseAction;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.config.entities.InterceptorMapping;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class BaseInterceptor extends AbstractInterceptor {
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		Object action = invocation.getAction();
		if (action instanceof BaseAction) {
			((BaseAction) action).setRequest(request);
			((BaseAction) action).setResponse(response);
		}
		String ret = null;
		ret = invocation.invoke();
		if (action instanceof BaseAction) {
			/*
			 * 操作日志
			 */
			if (invocation.getStack().findValue("exception") != null) {
				System.out.println(invocation.getStack().findValue("exception"));
			}
		}
		
		StringBuilder actionString = new StringBuilder();
		ActionProxy proxy = invocation.getProxy();
		List<InterceptorMapping> intercepterMapping = proxy.getConfig().getInterceptors();
		if (intercepterMapping != null && !intercepterMapping.isEmpty()) {
			Interceptor interceptor = null;
			for (InterceptorMapping map : intercepterMapping) {
				interceptor = map.getInterceptor();
			}
		}
		String namespace = proxy.getNamespace();
		actionString.append(namespace);
		if (namespace != null && namespace.trim().length() > 0 && !"/".equals(namespace)) {
			actionString.append("/");
		}
		actionString.append(proxy.getActionName()).append(".").append(DefaultSettings.get("struts.action.extension"));
		if (!"/system/control.dhtml".equals(actionString.toString()) && !"/database/getCrawlId.dhtml".equals(actionString.toString())) {
			System.out.println("\n");
			System.out.println("action:    " + actionString.toString());
			System.out.println("class :    " + proxy.getConfig().getClassName());
			System.out.println("method:    " + proxy.getConfig().getMethodName());
			com.opensymphony.xwork2.config.entities.ResultConfig config = proxy.getConfig().getResults() != null ? proxy.getConfig().getResults().get(ret == null ? "" : ret) : null;
			System.out.println("result   : " + (config == null ? "null" : (config.getParams() == null ? "null" : config.getParams().get("location"))) + "\n");
		}
		return ret;
	}
}
